import { cadAppLog } from '@amcax/base';

type Status = 'pending' | 'fullfiled'; // 状态  进行中 // 状态  成功
type Task = () => Promise<void>;
class SuperTask {
  private task: {
    task: Task;
    resolve: (value: unknown) => void;
    reject: (value: unknown) => void;
  }[];
  public runCount: number;
  public status: Status;
  private paralleCount: number;
  static instance: SuperTask;
  constructor(option: number) {
    this.task = [];
    this.runCount = 0;
    this.paralleCount = option;
  }
  add(task: Task) {
    return new Promise((resolve, reject) => {
      this.status = 'pending';
      this.task.push({
        task,
        resolve,
        reject,
      });
      this._run();
    });
  }
  _run() {
    while (this.task.length > 0 && this.runCount < this.paralleCount) {
      this.runCount++;
      const { task, resolve, reject } = this.task.shift();
      task()
        .then(resolve, reject)
        .finally(() => {
          this.runCount--;
          this._run();
          if (this.runCount <= 1) {
            this.status = 'fullfiled';
          }
        });
    }
  }
  static getInstance(taskCount = 10): SuperTask {
    if (!this.instance) {
      this.instance = new SuperTask(taskCount);
    }
    return this.instance;
  }
}

export const superTask = () => {
  return SuperTask.getInstance();
};

export function addTask(requestFn: Task, count) {
  superTask()
    .add(() => requestFn())
    .then(() => {
      cadAppLog(`任务${count}完成`);
    });
}
